'use strict';
// updateScore 云函数
const {
	verifyToken
} = require("wx-common");

exports.main = async (event, context) => {
	const db = uniCloud.database();
	const dbCmd = db.command;

	const {
		openid,
		scoreChange
	} = event;

	// 查询用户当前积分
	const user = await db.collection('users').where({
		openid
	}).get();
	if (user.affectedDocs === 0) {
		return {
			code: -1,
			message: '用户不存在'
		};
	}
	
	const payload = verifyToken(token);
	const currentScore = user.data[0].score;

	// 计算新的积分值
	const newScore = currentScore + scoreChange;

	// 更新用户的积分
	const updateRes = await db.collection('users').where({
		openid
	}).update({
		score: newScore
	});

	if (updateRes.updated === 1) {
		return {
			code: 0,
			message: '积分更新成功'
		};
	} else {
		return {
			code: -1,
			message: '积分更新失败'
		};
	}
};